package com.xxx.video.dynamic.fragments;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.ConcatAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.gms.tasks.OnSuccessListener;
import com.xxx.video.R;
import com.xxx.video.commen.adapters.BaseRecycleViewAdapter;
import com.xxx.video.commen.configs.UserManager;
import com.xxx.video.commen.events.LoginSuccessEvent;
import com.xxx.video.commen.fragments.BaseFragment;
import com.xxx.video.commen.utils.ListUtils;
import com.xxx.video.commen.utils.LocationUtils;
import com.xxx.video.commen.utils.StatusBarUtil;
import com.xxx.video.commen.utils.StringUtils;
import com.xxx.video.commen.views.recyclerviews.RefreshRecyclerView;
import com.xxx.video.dynamic.activitys.AddContactsFriendsActivity;
import com.xxx.video.dynamic.activitys.DynamicDetailsActivity;
import com.xxx.video.dynamic.activitys.MyFriendActivity;
import com.xxx.video.dynamic.activitys.PeopleNearbyActivity;
import com.xxx.video.dynamic.activitys.PersonInfoActivity;
import com.xxx.video.dynamic.activitys.RecommendFriendActivity;
import com.xxx.video.dynamic.adapters.DynamicListAdapter;
import com.xxx.video.dynamic.adapters.PeopleNearbyAdapter;
import com.xxx.video.dynamic.adapters.RecommendFriendAdapter;
import com.xxx.video.dynamic.beans.FriendListBean;
import com.xxx.video.dynamic.presenters.DynamicPresenter;
import com.xxx.video.dynamic.presenters.IDynamicView;
import com.xxx.video.login.activitys.LoginActivity;
import com.xxx.video.mine.beans.DynamicListBean;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

public class DynamicFragment extends BaseFragment<DynamicPresenter> implements IDynamicView,
        RefreshRecyclerView.OnRecyclerViewRefreshOrLoadMoreListener {

    @BindView(R.id.iv_actionbar_left_icon)
    ImageView ivActionbarLeftIcon;
    @BindView(R.id.tv_actionbar_left_tile)
    TextView tvActionbarLeftTile;
    @BindView(R.id.iv_actionbar_right_icon)
    ImageView ivActionbarRightIcon;
    @BindView(R.id.tv_actionbar_right_title)
    TextView tvActionbarRightTitle;
    @BindView(R.id.v_actionbar_bottom_line)
    View vActionbarBottomLine;
    @BindView(R.id.cl_actionbar)
    ConstraintLayout clActionbar;
    @BindView(R.id.cl_dynamic_fragment_contacts_add_friends)
    ConstraintLayout clDynamicFragmentContactsAddFriends;
    @BindView(R.id.cl_dynamic_fragment_people_nearby)
    ConstraintLayout clDynamicFragmentPeopleNearby;
    @BindView(R.id.rcv_dynamic_fragment_list)
    RefreshRecyclerView rcvDynamicFragmentList;
    /**
     * page
     */
    private int page = 1;

    private ConcatAdapter mConcatAdapter;
    /**
     * location
     */
    private Location mLocation;
    private DynamicListAdapter mDynamicListAdapter;
    private PeopleNearbyAdapter mPeopleNearbyAdapter;
    private RecommendFriendAdapter mRecommendFriendAdapter;

    @Override
    public void initToolbarData() {
        super.initToolbarData();
        clActionbar.setVisibility(View.VISIBLE);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) clActionbar.getLayoutParams();
        layoutParams.setMargins(0, StatusBarUtil.getInstance().getStatusBarHeight(Objects.requireNonNull(getActivity())), 0, 0);
        clActionbar.setLayoutParams(layoutParams);
        ivActionbarLeftIcon.setVisibility(View.GONE);
        tvActionbarLeftTile.setText(StringUtils.getInstance().getString(R.string.title_dynamic_fragment));
        vActionbarBottomLine.setVisibility(View.VISIBLE);
        ivActionbarRightIcon.setVisibility(View.VISIBLE);
        ivActionbarRightIcon.setImageResource(R.drawable.icon_dynamic_fragment_right);
    }

    @Override
    protected DynamicPresenter createPresenter() {
        return new DynamicPresenter(Objects.requireNonNull(getActivity()), this);
    }

    public static DynamicFragment newInstance(Bundle args) {
        DynamicFragment fragment = new DynamicFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getContentLayout() {
        return R.layout.fragment_dynamic;
    }

    @Override
    public void initData(Bundle extras) {
        if (!UserManager.getInstance().isLogin()) {
            showRootLayoutStatus(3);
            return;
        }
        initList();
        getPresenter().recommendFriends();
        getPresenter().getDynamicList(page);
    }

    @Override
    public void showRootLayoutStatus(int status) {
        showLayoutStatus(status);
    }

    @OnClick({R.id.iv_actionbar_right_icon, R.id.cl_dynamic_fragment_contacts_add_friends, R.id.cl_dynamic_fragment_people_nearby})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_actionbar_right_icon:
                startMyFriendActivity();
                break;
            case R.id.cl_dynamic_fragment_contacts_add_friends:
                startAddContactsFriendsActivity();
                break;
            case R.id.cl_dynamic_fragment_people_nearby:
                startPeopleNearbyActivity();
                break;
            default:
                break;
        }
    }

    @Override
    public void initList() {
        rcvDynamicFragmentList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mConcatAdapter = new ConcatAdapter();
        rcvDynamicFragmentList.setAdapter(mConcatAdapter);
        rcvDynamicFragmentList.setOnRecyclerViewRefreshOrLoadMoreListener(this);
        /*
         * is have location permission
         */
        if (ActivityCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            /*
             * get location
             */
            initLocation();
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            }
        }
    }

    @Override
    public void initPeopleNearbyList(FriendListBean.PageBean pageBean) {
        showRootLayoutStatus(1);
        if (ListUtils.isEmpty(pageBean.list)) {
            return;
        }
        if (mPeopleNearbyAdapter == null) {
            mPeopleNearbyAdapter = new PeopleNearbyAdapter(Objects.requireNonNull(getActivity()));
            mConcatAdapter.addAdapter(0, mPeopleNearbyAdapter);
            mPeopleNearbyAdapter.setOnItemClickListener((BaseRecycleViewAdapter.OnItemClickListener<FriendListBean.PageBean.ListBean>) (listBean, position, type) -> {
                if (type == 1) {
                    startPeopleNearbyActivity();
                } else if (type == 0) {
                    startPersonInfoActivity(listBean.userId);
                } else if (type == 3) {
                    getPresenter().addFriends(listBean, position, 1);
                }
            });
        }
        mPeopleNearbyAdapter.setFriendListData(pageBean.list);
    }

    @Override
    public void initRecommendFriendList(FriendListBean.PageBean pageBean) {
        showRootLayoutStatus(1);
        if (ListUtils.isEmpty(pageBean.list)) {
            return;
        }
        if (mRecommendFriendAdapter == null) {
            mRecommendFriendAdapter = new RecommendFriendAdapter(Objects.requireNonNull(getActivity()));
            if (mConcatAdapter.getAdapters().size() == 0) {
                mConcatAdapter.addAdapter(mRecommendFriendAdapter);
            } else if (mConcatAdapter.getAdapters().size() == 1) {
                if (mConcatAdapter.getAdapters().get(0) instanceof PeopleNearbyAdapter) {
                    mConcatAdapter.addAdapter(mRecommendFriendAdapter);
                } else {
                    mConcatAdapter.addAdapter(0, mRecommendFriendAdapter);
                }
            } else if (mConcatAdapter.getAdapters().size() == 2) {
                mConcatAdapter.addAdapter(1, mRecommendFriendAdapter);
            }
        }

        mRecommendFriendAdapter.setFriendListData(pageBean.list);
        mRecommendFriendAdapter.setOnItemClickListener((BaseRecycleViewAdapter.OnItemClickListener<FriendListBean.PageBean.ListBean>) (listBean, position, type) -> {
            if (type == 1) {
                startRecommendFriendActivity();
            } else if (type == 0) {
                startPersonInfoActivity(listBean.userId);
            } else if (type == 3) {
                getPresenter().addFriends(listBean, position, 2);
            }
        });
    }

    @Override
    public void startMyFriendActivity() {
        if (!UserManager.getInstance().isLogin()) {
            intent2Activity(LoginActivity.class);
            return;
        }
        intent2Activity(MyFriendActivity.class);
    }

    @Override
    public void startPeopleNearbyActivity() {
        intent2Activity(PeopleNearbyActivity.class);
    }

    @Override
    public void startRecommendFriendActivity() {
        intent2Activity(RecommendFriendActivity.class);
    }

    @Override
    public void startAddContactsFriendsActivity() {
        intent2Activity(AddContactsFriendsActivity.class);
    }

    @Override
    public void startPersonInfoActivity(String userId) {
        Bundle bundle = new Bundle();
        bundle.putString("Id", userId);
        intent2Activity(PersonInfoActivity.class, bundle);
    }

    @Override
    public void initData2View(DynamicListBean successOb) {
        showRootLayoutStatus(1);
        rcvDynamicFragmentList.resetState();
        if (mDynamicListAdapter == null) {
            mDynamicListAdapter = new DynamicListAdapter(getActivity());
            mConcatAdapter.addAdapter(mDynamicListAdapter);
            mDynamicListAdapter.setOnItemClickListener((BaseRecycleViewAdapter.OnItemClickListener<DynamicListBean.PageBean.ListBean>) (listBean, position, type) -> startVideoDetailsActivity(listBean.fId));
        }
        if (page == 1) {
            mDynamicListAdapter.setData(successOb.page.list);
        } else {
            mDynamicListAdapter.addData(successOb.page.list);
        }
        if (!ListUtils.isEmpty(successOb.page.list) && successOb.page.list.size() < 10) {
            rcvDynamicFragmentList.setNoMoreData();
        }
    }

    @Override
    public void initLocation() {
        LocationUtils.getLocation(getActivity(), (OnSuccessListener<Location>) location -> {
            if (location != null) {
                mLocation = location;
                getPresenter().nearbyUser(String.valueOf(1), String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude()));
            }
        });
    }

    @Override
    public void startVideoDetailsActivity(String videoId) {
        Bundle bundle = new Bundle();
        bundle.putString("Id", videoId);
        intent2Activity(DynamicDetailsActivity.class, bundle);
    }

    @Override
    public void addFriendSuccess(int position, int type) {
        if (type == 1) {
            if (mPeopleNearbyAdapter != null) {
                mPeopleNearbyAdapter.addFriendSuccess(position);
            }
        } else if (type == 2) {
            if (mRecommendFriendAdapter != null) {
                mRecommendFriendAdapter.addFriendSuccess(position);
            }
        }
    }

    @Override
    public void onRecyclerviewRefresh() {
        page = 1;
        getPresenter().recommendFriends();
        getPresenter().getDynamicList(page);
    }

    @Override
    public void onRecyclerviewLoadMore() {
        page++;
        getPresenter().getDynamicList(page);
    }

    @Override
    public boolean isOpenEventBus() {
        return true;
    }

    @Override
    public void refreshData(Bundle extras) {
        getPresenter().recommendFriends();
        getPresenter().getDynamicList(page);
    }

    /**
     * login Success
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginSuccess(LoginSuccessEvent loginSuccessEvent) {
        page = 1;
        showRootLayoutStatus(1);
        getPresenter().recommendFriends();
        getPresenter().getDynamicList(page);
    }
}
